package com.cheer.ba.view.activity;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.model.CityModel;
import com.cheer.ba.model.DailyModel;
import com.cheer.ba.model.ProvinceModel;
import com.cheer.ba.model.WeatherModel;
import com.cheer.ba.presenter.impl.HomePresenter;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.service.LocationService;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.utils.WeatherUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.pickerview.OptionsPickerView;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 天气预报界面
 *
 * @author HQ
 *         created at 2017/4/1 0001 14:54
 */
public class WeatherAty extends BaseCommAty {

    @BindView(R.id.id_weather_listview)
    ListView mListView;
    private CommonAdapter<DailyModel> mAdapter;
    private List<DailyModel> mWeathers = new ArrayList<DailyModel>();
    //定位地址
    TextView mTxtLocation;
    //更新时间
    TextView mTxtUpTime;
    //白天温度
    TextView mTxtDayTemp;
    //夜间温度
    TextView mTxtNightTemp;
    //天气图标
    ImageView mImgWeather;
    //天气情况
    TextView mTxtWeather;
    //空气质量
    TextView mTxtQuality;
    //风力情况
    TextView mTxtWinddirect;
    //风力大小
    TextView mTxtWindpower;
    //空气湿度
    TextView mTxtHumidity;

    //定位服务
    private LocationService mLocationService;

    //记录定位省
    private String mSaveProvince;
    //记录定位城市
    private String mSaveCity;
    //记录当前纬度
    private double mCurrentLat;
    //记录当前经度
    private double mCurrentLon;

    //省市选择器
    private OptionsPickerView pvOptions;
    //存储省级城市数据
    private ArrayList<String> mSaveP = new ArrayList<String>();
    //存储市级城市数据
    private ArrayList<ArrayList<String>> mSaveC = new ArrayList<ArrayList<String>>();

    private OilMealPresenter mOilMealPresenter;

    @Override
    protected boolean isSupportSwipeback() {
        return false;
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_weather, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new HomePresenter();
        mOilMealPresenter = new OilMealPresenter();
        mOilMealPresenter.attachView(this);
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.weather_forecast));
        View mHeadView = getLayoutInflater().inflate(R.layout.head_view_weather, null);
        mTxtLocation = (TextView) mHeadView.findViewById(R.id.id_location_txt);
        mTxtUpTime = (TextView) mHeadView.findViewById(R.id.id_time_txt);
        mTxtDayTemp = (TextView) mHeadView.findViewById(R.id.id_temp_day_txt);
        mTxtNightTemp = (TextView) mHeadView.findViewById(R.id.id_temp_night_txt);
        mImgWeather = (ImageView) mHeadView.findViewById(R.id.id_weather_img);
        mTxtWeather = (TextView) mHeadView.findViewById(R.id.id_weather_desc_txt);
        mTxtQuality = (TextView) mHeadView.findViewById(R.id.id_weather_quality_txt);
        mTxtWinddirect = (TextView) mHeadView.findViewById(R.id.id_weather_winddirect_txt);
        mTxtWindpower = (TextView) mHeadView.findViewById(R.id.id_weather_windpower_txt);
        mTxtHumidity = (TextView) mHeadView.findViewById(R.id.id_weather_humidity_txt);
        mListView.addHeaderView(mHeadView);

        mAdapter = new CommonAdapter<DailyModel>(aty, mWeathers, R.layout.adp_weather) {
            @Override
            public void convert(ViewHolder helper, DailyModel item) {
                if (null != item) {
                    helper.setText(R.id.id_weather_week_txt, item.week);
                    helper.setText(R.id.id_weather_time_txt, item.date);
                    helper.setBackgroundResource(R.id.id_weather_img, WeatherUtil.returnIcon(item.day.img));
                    helper.setText(R.id.id_weather_day_txt, item.day.weather);
                    helper.setText(R.id.id_temp_day_txt, item.day.temphigh.contains("℃") ? item.day.temphigh : (item.day.temphigh + "℃"));
                    helper.setText(R.id.id_temp_night_txt, item.night.templow.contains("℃") ? item.night.templow : (item.night.templow + "℃"));
                }
            }
        };
        mListView.setAdapter(mAdapter);

        initChooseCityDialog();
    }

    /**
     * 初始化选择器
     */
    private void initChooseCityDialog() {
        //选择器
        pvOptions = new OptionsPickerView(this);
        //获得省级数据
        List<ProvinceModel> provinces = (List<ProvinceModel>) mOilMealPresenter.getData(4,false);
        if (null != provinces && !provinces.isEmpty()) {
            mSaveP.clear();
            for (ProvinceModel p : provinces) {
                mSaveP.add(p.mProvinceName);
            }
            //获得市级数据
            List<CityModel> citys = (List<CityModel>) mOilMealPresenter.getData(5,false);
            if (null != citys && !citys.isEmpty()) {
                mSaveC.clear();
                for (ProvinceModel province : provinces) {
                    ArrayList<String> mC = new ArrayList<String>();
                    for (CityModel city : citys) {
                        if (TextUtils.equals(province.mPId, city.mPID)) {
                            mC.add(city.mCityName);
                        }
                    }
                    mSaveC.add(mC);
                }
            }
        }
        if (!mSaveP.isEmpty() && !mSaveC.isEmpty()) {
            //设置默认选中的三级项目
            //监听确定选择按钮
            int a = 16;
            int b = 0;
            if (!StringUtils.isEmpty(mSaveProvince)) {
                for (int i = 0; i < mSaveP.size(); i++) {
                    if (mSaveP.get(i).contains(mSaveProvince)) {
                        a = i;
                    }
                }
            }
            if (!StringUtils.isEmpty(mSaveCity)) {
                for (int i = 0; i < mSaveC.get(a).size(); i++) {
                    if (mSaveC.get(a).get(i).contains(mSaveCity)) {
                        b = i;
                    }
                }
            }
            //二级联动效果
            pvOptions.setPicker(mSaveP, mSaveC, true);
            //设置二级单位
//            pvOptions.setLabels("省", "市");
            pvOptions.setCyclic(false, false, false);
            pvOptions.setSelectOptions(a, b);
            pvOptions.setTextSize(18);
            pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3) {
                    //返回的分别是三个级别的选中位置
                    mSaveProvince = mSaveP.get(options1);
                    mSaveCity = mSaveC.get(options1).get(option2);
                    mTxtLocation.setText(mSaveCity);
                    getWeatherDay(mSaveCity, "");
                }
            });
        }
    }

    @Override
    public void initData() {
        mLocationService = ((App) getApplication()).mLocationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocationService.registerListener(mListener);
        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        //定位
        mLocationService.start();

        setTitleRight("其他城市", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseCity();
            }
        });
    }

    /**
     * 选择城市
     */
    private void chooseCity() {
        if (null != pvOptions) {
            if (!mSaveP.isEmpty() && !mSaveC.isEmpty()) {
                pvOptions.show();
                return;
            }
        }
        ToastUtil.showToast("获取数据错误");
    }

    /**
     * 获得天气
     *
     * @param cityName
     * @param location
     */
    public void getWeatherDay(String cityName, String location) {
        ((HomePresenter) presenter).searchWearth(cityName, location);
    }

    public void onClick(View mView) {
        switch (mView.getId()) {
            //定位
            case R.id.id_location_txt:
                mLocationService.start();
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            WeatherModel model = (WeatherModel) t;
            String time = StringUtils.dateToStamp(model.updatetime, "yyyy-MM-dd HH:mm");
            mTxtUpTime.setText(StringUtils.formatDisplayTime(time, "yyyy-MM-dd HH:mm:ss"));
            mTxtDayTemp.setText(model.temphigh.contains("℃") ? model.temphigh : (model.temphigh + "℃"));
            mTxtNightTemp.setText(model.templow.contains("℃") ? model.templow : (model.templow + "℃"));
            mImgWeather.setBackgroundResource(WeatherUtil.returnIcon(model.img));
            mTxtWeather.setText(model.weather);
            mTxtQuality.setText(model.aqi.quality);
            mTxtWinddirect.setText(model.winddirect);
            mTxtWindpower.setText(model.windpower.contains("级") ? model.windpower : (model.windpower + "级"));
            mTxtHumidity.setText(model.humidity.contains("%") ? model.humidity : (model.humidity + "%"));
            List<DailyModel> dailies = model.daily;
            if (null != dailies && !dailies.isEmpty()) {
                mWeathers.clear();
                mWeathers.addAll(dailies);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void handlerByPage(int flag1, int flag2) {
        super.handlerByPage(flag1, flag2);
        if (flag2 == CodeStatus.Gegeneral.ERROR_NET) {
            ToastUtil.showToast("没有网络");
        } else {
            ToastUtil.showToast("获取天气数据失败");
        }
    }

    @Override
    protected void onStop() {
        //注销监听
        mLocationService.unregisterListener(mListener);
        //停止定位服务
        mLocationService.stop();
        super.onStop();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                //省
                mSaveProvince = location.getProvince();
                // 城市
                mSaveCity = location.getCity();

                //当前纬度
                mCurrentLat = location.getLatitude();
                //当前经度
                mCurrentLon = location.getLongitude();
                if (location.getLocType() == BDLocation.TypeServerError) {
                    ToastUtil.showToast("服务端网络定位失败");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    ToastUtil.showToast("网络不同导致定位失败，请检查网络是否通畅");
                }
                mTxtLocation.setText(mSaveCity);
                if (mCurrentLat != 0 && mCurrentLon != 0 && !StringUtils.isEmpty(mSaveCity) && !mSaveCity.contains("null")) {
                    getWeatherDay(mSaveCity, mCurrentLat + "," + mCurrentLon);
                } else {
                    mTxtLocation.setText("定位失败");
                    mCurrentLat = 0;
                    mCurrentLon = 0;
                    mSaveCity = "武汉";
                    getWeatherDay(mSaveCity, "");
                }
            } else {
                mTxtLocation.setText("定位失败");
                mCurrentLat = 0;
                mCurrentLon = 0;
                mSaveCity = "武汉";
                getWeatherDay(mSaveCity, "");
            }
            mLocationService.stop();
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };
}
